// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const canJu = db.collection("canju")

const countPeople = (arr, key) => {
  return arr.reduce((acc, current) => {
    const value = current[key];
    if (!acc.set.has(value)) {
      acc.set.add(value);
      acc.count++;
    }
    return acc;
  }, { set: new Set(), count: 0 }).count;
}
// 云函数入口函数
// 残局函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  const totalNum = await canJu.where({
    openid: wxContext.OPENID
  }).count()

  const myCanJuInfo = await canJu.where({
      openid: wxContext.OPENID
    })
    .orderBy('due', 'desc')
    .skip(event.pageNum * (event.currentPage - 1))
    .limit(event.pageNum)
    .field({
      progressTipsNum: true,
      totalScoreRest: true,
      level:true,
      playInfo: true,
      win:true
    })
    .get()

    myCanJuInfo.data.forEach(item => {
      const count = countPeople(item.playInfo, 'openid');
      item.countPeople = count
    })

  return {
    code: 'myCanJuOK',
    res: {
      totalNum: totalNum.total,
      myCanJuInfo: myCanJuInfo.data
    }
  }


}
